#!/usr/bin/env python
# -*- coding: utf-8 -*-


__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_36"
__date__    = "2014/01/05"
__license__ = 'LGPL'

# ------------------------------------------------------------
## インポート
# Python
import sys
sys.path.append(".")
sys.path.append("src")

import ConfigParser
import traceback
import codecs

# Mikan
from mikan.orm import new_mikan_orm

def _loader(name):
	try:
		mod = __import__(name)
	except:
		mod_list = name.split('.')
		mod = __import__('.'.join(mod_list[:-1]))

	components = name.split('.')
	for comp in components[1:]:
		mod = getattr(mod, comp)
	return mod


def _output(filename, text):
	mode = 'w'

	fw = codecs.open(filename, mode, "utf-8")
	fw.write(text)
	fw.flush()
	fw.close()

# ------------------------------------------------------------
## メイン処理
if __name__ == '__main__':
	config = ConfigParser.SafeConfigParser()
	try:
		config.readfp(codecs.open("etc/mikan.ini", "r", "utf8"))
	except:
		print(traceback.format_exc())

	ini = ConfigParser.SafeConfigParser()
	try:
		ini.readfp(codecs.open("./etc/orm.ini", "r", "utf8"))
	except:
		print(traceback.format_exc())

	try:
		t = config.get("orm", "type")
		orm = new_mikan_orm(None, t)
		orm.setup(config, "orm")
		orm.setup_orm(ini)
	except Exception, e:
		print(traceback.format_exc())

	c = _loader(sys.argv[1])
	items = orm.gets(c)
	_output(sys.argv[2], orm.exports("json", items))

#	f = open(sys.argv[1])
#	d = f.read().decode("utf-8")
#	f.close()
#	print d

#	items = orm.imports("json", d, True)
#	for item in items:
#		print item.values

#	orm.commit()
